/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.security;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.yami.shop.api.util.JifenmallAuthUtil;
import com.yami.shop.bean.model.LoginHist;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.param.UserRegisterParam;
import com.yami.shop.common.util.Json;
import com.yami.shop.security.service.YamiUser;
import com.yami.shop.security.service.YamiUserDetailsService;
import com.yami.shop.service.LoginHistService;
import com.yami.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;

/**
 * 账号密码登录
 */
@Component
public class WebLoginAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    private final YamiUserDetailsService yamiUserDetailsService;

    private final WxMaService wxMaService;
    @Autowired
    private Environment environment;
    @Autowired
    private JifenmallAuthUtil jifenmallAuthUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private LoginHistService loginHistService;

    @Autowired
    public WebLoginAuthenticationFilter(YamiUserDetailsService yamiUserDetailsService, WxMaService wxMaService) {
        super("/webLogin");
        this.yamiUserDetailsService = yamiUserDetailsService;
        this.wxMaService = wxMaService;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!ServletUtil.METHOD_POST.equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        String requestBody = getStringFromStream(request);

        if (StrUtil.isBlank(requestBody)) {
            throw new AuthenticationServiceException("无法获取输入信息");
        }
        WebAuthenticationToken authentication = Json.parseObject(requestBody, WebAuthenticationToken.class);
        //用户名 员工编号
        String principal = String.valueOf(authentication.getPrincipal());
        //密码
        String loginPassword = String.valueOf(authentication.getCredentials());

        YamiUser loadedUser;
//        生产环境使用鉴权
        if (Arrays.asList(environment.getActiveProfiles())
                .contains("prod")) {
            //鉴权
            jifenmallAuthUtil.auth(principal, loginPassword);

            User one = userService.getByUserCode(principal);
            //鉴权没报错，没有用户信息就插入默认的
            if (one == null) {
                UserRegisterParam userRegisterParam = new UserRegisterParam();
                userRegisterParam.setUserCode(principal);
                userRegisterParam.setUserMail(RandomUtil.randomNumbers(10) + "@123.com");
                userRegisterParam.setPassword("123");
                userRegisterParam.setNickName(principal);
                userService.insertUser(userRegisterParam);
                one = userService.getByUserCode(principal);
            }

            loadedUser = new YamiUser(one.getUserId(), one.getLoginPassword(), one.getStatus() == 1);
            loadedUser.setName(principal);

        } else {
//            开发环境使用自己数据库的账号密码登录
            loadedUser = yamiUserDetailsService.loadUserByUserMail(principal, loginPassword);
        }

//        保存登录记录
        LoginHist loginHist = new LoginHist();
        loginHist.setUserCode(principal);
        loginHist.setUserId(loadedUser.getUserId());
        loginHist.setLoginTime(new Date());
        loginHistService.save(loginHist);
        WebAuthenticationToken result = new WebAuthenticationToken(loadedUser, authentication.getCredentials());
        result.setDetails(authentication.getDetails());
        return result;
    }


    private String getStringFromStream(HttpServletRequest req) {
        ServletInputStream is;
        try {
            is = req.getInputStream();
            int nRead = 1;
            int nTotalRead = 0;
            byte[] bytes = new byte[10240];
            while (nRead > 0) {
                nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
                if (nRead > 0) {
                    nTotalRead = nTotalRead + nRead;
                }
            }
            return new String(bytes, 0, nTotalRead, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    @Autowired
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
        super.setAuthenticationSuccessHandler(successHandler);
    }

    @Override
    @Autowired
    public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
        super.setAuthenticationFailureHandler(failureHandler);
    }
}
